package com.ruoyi.web.ydz.util.sensitiveFilter;

import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.SegToken;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/*敏感词过滤util*/
@Component
public class FileToList {

    @Resource
    private RedisCache redisCache;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public static HashSet<String> readFileToList(String filePath) throws IOException {
        HashSet<String> lines = new HashSet<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    // 去掉行首尾空白
                    lines.add(line.trim());
                }
            }
        }
        return lines;
    }

    public boolean isMemberOfSet(String setName, String member) {
        // 使用 execute 方法执行 SISMEMBER 命令
        return redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            // 将字符串转换为字节数组
            byte[] key = setName.getBytes();
            byte[] value = member.getBytes();
            // 调用 Redis 的 SISMEMBER 命令
            return connection.sIsMember(key, value);
        });
    }

    //@PostConstruct
    //@Transactional
    public void reve() throws IOException {

        File directory = new File("ruoyi-admin/src/main/resources");
        String reportPath = directory.getCanonicalPath();
        String filePath = reportPath + "/sensitive_words.txt";

        try {
            if (new File(filePath).exists()) {
                System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(new Date()) + "敏感词数据开始导入redis");
                redisCache.deleteObject("sys_dict:sensitiveTerms");
                HashSet<String> lines = readFileToList(filePath);
                redisCache.setCacheSet("sys_dict:sensitiveTerms", lines);

                System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(new Date()) + "敏感词数据导入redis成功");
            }else{
                System.out.println("敏感词数据文件不存在" + filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*字符串过滤敏感字符*/
    public String filterStr(String str) {
        JiebaSegmenter segmenter = new JiebaSegmenter();

        String compositionStr = str;
        // 精确模式
        List<SegToken> segTokens = segmenter.process(str, JiebaSegmenter.SegMode.INDEX);

        // 打印分词结果
        for (SegToken token : segTokens) {
            String tokenStr = token.word.getToken();
            boolean memberOfSet = this.isMemberOfSet("sys_dict:sensitiveTerms", "\"" + tokenStr + "\"");
            if (memberOfSet) {

                // 需要替换的*
                int length = tokenStr.length();
                StringBuilder replacement = new StringBuilder();
                for (int i = 0; i < length; i++) {
                    replacement.append('*');
                }
                // 替换起止下标
                int start = token.startOffset;
                // 替换结束下标
                int end = token.endOffset;
                // 拼接新的字符串
                compositionStr = compositionStr.substring(0, start) + replacement.toString() + compositionStr.substring(end);

            }
        }

        return compositionStr;
    }
}